/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-06-12 14:59:08
 * @LastEditors: jqm123 2289662078@qq.com
 * @LastEditTime: 2025-08-07 09:41:44
 * @FilePath: /mobile_demo_v3/src/stores/user.store.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import api from "@/api/api";
import { isZxcxAPP, zxcxStartLocation } from "@/utils/zxcxWebkit";
import { defineStore } from "pinia";
import { useCommonStore } from "./common.store";

export const useUserStore = defineStore("user-store", {
  state: () => ({
    userData: JSON.parse(sessionStorage.getItem("userData")) || {},
    token: sessionStorage.getItem("token") || "",
    carList: JSON.parse(sessionStorage.getItem("carList")) || [],
    locationInfo: JSON.parse(sessionStorage.getItem("location")) || {},
    addressList: JSON.parse(sessionStorage.getItem("address")) || [],
  }),
  getters: {},
  actions: {
    async login(userId) {
      if (Object.keys(this.userData).length > 0) {
        return;
      }
      const commonStore = useCommonStore();
      let res = await api.login({ userId });
      if (!res.token) return;
      this.setToken(res.token);
      this.setUserData(res);
      let res2 = await api.user.getCarList();
      this.setCarList(res2.data);
      commonStore.setIndex(0);
      if (isZxcxAPP()) {
        let loc = await zxcxStartLocation();
        this.setLocation(loc);
      }
    },
    setToken(token) {
      this.token = token;
      sessionStorage.setItem("token", token);
    },

    setUserData(res) {
      this.userData = {
        avatar: res.avatar,
        phone: res.phone,
        userName: res.userName,
        role: res.roles,
        id: res.userId,
        isVip: res.memberFlag,
        vip_start: res?.memberStart,
        vip_end: res?.memberEnd,
      };
      sessionStorage.setItem("userData", JSON.stringify(this.userData));
    },

    setCarList(carInfo) {
      this.carList = carInfo;
      sessionStorage.setItem("carList", JSON.stringify(carInfo));
    },

    setLocation(data) {
      this.locationInfo = data;
      sessionStorage.setItem("location", JSON.stringify(data));
    },
    setAddress(data) {
      this.addressList = data;
      sessionStorage.setItem("address", JSON.stringify(data));
    },
  },
});
